<template>
  <div class="problem-list">
    <!-- 筛选和搜索区域 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索题目名称或标签..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-right">
        <el-select v-model="difficultyFilter" placeholder="难度" @change="handleFilter">
          <el-option label="全部难度" value="" />
          <el-option label="简单" value="简单" />
          <el-option label="中等" value="中等" />
          <el-option label="困难" value="困难" />
        </el-select>
        
        <el-select v-model="statusFilter" placeholder="状态" @change="handleFilter">
          <el-option label="全部状态" value="" />
          <el-option label="已解决" value="solved" />
          <el-option label="尝试过" value="attempted" />
          <el-option label="未开始" value="not_started" />
        </el-select>
        
        <el-select v-model="tagFilter" placeholder="标签" @change="handleFilter">
          <el-option label="全部标签" value="" />
          <el-option 
            v-for="tag in allTags" 
            :key="tag"
            :label="tag" 
            :value="tag" 
          />
        </el-select>
        
        <el-select v-model="sortBy" placeholder="排序" @change="handleSort">
          <el-option label="默认排序" value="default" />
          <el-option label="难度升序" value="difficulty_asc" />
          <el-option label="难度降序" value="difficulty_desc" />
          <el-option label="通过率升序" value="acceptance_asc" />
          <el-option label="通过率降序" value="acceptance_desc" />
          <el-option label="提交数升序" value="submissions_asc" />
          <el-option label="提交数降序" value="submissions_desc" />
        </el-select>
      </div>
    </div>

    <!-- 题目统计 -->
    <div class="problem-stats">
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-number">{{ filteredProblems.length }}</div>
          <div class="stat-label">题目总数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ solvedCount }}</div>
          <div class="stat-label">已解决</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ attemptedCount }}</div>
          <div class="stat-label">尝试过</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ Math.round(solvedCount / filteredProblems.length * 100) }}%</div>
          <div class="stat-label">完成率</div>
        </div>
      </div>
    </div>

    <!-- 题目列表 -->
    <div class="problems-container">
      <div class="problems-table">
        <el-table 
          :data="paginatedProblems" 
          style="width: 100%"
          @row-click="viewProblem"
        >
          <el-table-column width="60" align="center">
            <template #default="{ row }">
              <div class="status-indicator">
                <el-icon v-if="row.userStatus === 'solved'" class="solved">
                  <CircleCheck />
                </el-icon>
                <el-icon v-else-if="row.userStatus === 'attempted'" class="attempted">
                  <Warning />
                </el-icon>
                <div v-else class="not-started"></div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="id" label="题号" width="80" align="center" />
          
          <el-table-column prop="title" label="题目" min-width="200">
            <template #default="{ row }">
              <div class="problem-title-cell">
                <div class="title" @click.stop="viewProblem(row)">{{ row.title }}</div>
                <div class="tags">
                  <el-tag 
                    v-for="tag in row.tags.slice(0, 3)" 
                    :key="tag"
                    size="small"
                    effect="plain"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="difficulty" label="难度" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getDifficultyType(row.difficulty)" size="small">
                {{ row.difficulty }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="acceptanceRate" label="通过率" width="100" align="center">
            <template #default="{ row }">
              <span class="acceptance-rate">{{ row.acceptanceRate }}%</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="submissions" label="提交数" width="100" align="center">
            <template #default="{ row }">
              <span class="submissions-count">{{ formatNumber(row.submissions) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" @click.stop="viewProblem(row)">
                  查看题目
                </el-button>
                <el-button 
                  size="small" 
                  type="primary" 
                  @click.stop="solveProblem(row)"
                >
                  {{ row.userStatus === 'solved' ? '重新解题' : '开始解题' }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredProblems.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="filteredProblems.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 空状态 -->
      <div v-if="filteredProblems.length === 0" class="empty-state">
        <EmptyState
          image="/images/empty-problems.svg"
          title="暂无题目"
          description="当前筛选条件下没有找到相关题目"
        >
          <el-button @click="resetFilters">
            重置筛选
          </el-button>
        </EmptyState>
      </div>
    </div>

    <!-- 随机题目按钮 -->
    <div class="floating-actions">
      <el-button 
        type="primary" 
        circle 
        size="large"
        @click="randomProblem"
        class="random-btn"
      >
        <el-icon><Refresh /></el-icon>
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, CircleCheck, Warning, Refresh
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const difficultyFilter = ref('')
const statusFilter = ref('')
const tagFilter = ref('')
const sortBy = ref('default')
const currentPage = ref(1)
const pageSize = ref(50)

// 所有标签
const allTags = ref([
  '数组', '字符串', '链表', '树', '图', '哈希表', '栈', '队列',
  '动态规划', '贪心', '回溯', '分治', '二分查找', '排序', '数学',
  '位运算', '双指针', '滑动窗口', '递归', '迭代'
])

// 题目数据
const problems = ref([
  {
    id: 1,
    title: '两数之和',
    difficulty: '简单',
    tags: ['数组', '哈希表'],
    acceptanceRate: 49.2,
    submissions: 1250000,
    userStatus: 'solved'
  },
  {
    id: 2,
    title: '两数相加',
    difficulty: '中等',
    tags: ['链表', '数学'],
    acceptanceRate: 37.8,
    submissions: 980000,
    userStatus: 'attempted'
  },
  {
    id: 3,
    title: '无重复字符的最长子串',
    difficulty: '中等',
    tags: ['字符串', '滑动窗口', '哈希表'],
    acceptanceRate: 33.5,
    submissions: 850000,
    userStatus: null
  },
  {
    id: 4,
    title: '寻找两个正序数组的中位数',
    difficulty: '困难',
    tags: ['数组', '二分查找', '分治'],
    acceptanceRate: 39.1,
    submissions: 420000,
    userStatus: null
  },
  {
    id: 5,
    title: '最长回文子串',
    difficulty: '中等',
    tags: ['字符串', '动态规划'],
    acceptanceRate: 32.1,
    submissions: 750000,
    userStatus: 'attempted'
  },
  // 添加更多题目数据...
  ...Array.from({ length: 95 }, (_, i) => ({
    id: i + 6,
    title: `算法题目 ${i + 6}`,
    difficulty: ['简单', '中等', '困难'][Math.floor(Math.random() * 3)],
    tags: allTags.value.slice(0, Math.floor(Math.random() * 4) + 1),
    acceptanceRate: Math.floor(Math.random() * 60) + 20,
    submissions: Math.floor(Math.random() * 500000) + 10000,
    userStatus: Math.random() > 0.7 ? (Math.random() > 0.5 ? 'solved' : 'attempted') : null
  }))
])

// 计算属性
const filteredProblems = computed(() => {
  let filtered = problems.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(problem => 
      problem.title.toLowerCase().includes(keyword) ||
      problem.tags.some(tag => tag.toLowerCase().includes(keyword))
    )
  }

  // 难度筛选
  if (difficultyFilter.value) {
    filtered = filtered.filter(problem => problem.difficulty === difficultyFilter.value)
  }

  // 状态筛选
  if (statusFilter.value) {
    if (statusFilter.value === 'not_started') {
      filtered = filtered.filter(problem => !problem.userStatus)
    } else {
      filtered = filtered.filter(problem => problem.userStatus === statusFilter.value)
    }
  }

  // 标签筛选
  if (tagFilter.value) {
    filtered = filtered.filter(problem => problem.tags.includes(tagFilter.value))
  }

  // 排序
  switch (sortBy.value) {
    case 'difficulty_asc':
      filtered.sort((a, b) => {
        const order = { '简单': 1, '中等': 2, '困难': 3 }
        return order[a.difficulty] - order[b.difficulty]
      })
      break
    case 'difficulty_desc':
      filtered.sort((a, b) => {
        const order = { '简单': 1, '中等': 2, '困难': 3 }
        return order[b.difficulty] - order[a.difficulty]
      })
      break
    case 'acceptance_asc':
      filtered.sort((a, b) => a.acceptanceRate - b.acceptanceRate)
      break
    case 'acceptance_desc':
      filtered.sort((a, b) => b.acceptanceRate - a.acceptanceRate)
      break
    case 'submissions_asc':
      filtered.sort((a, b) => a.submissions - b.submissions)
      break
    case 'submissions_desc':
      filtered.sort((a, b) => b.submissions - a.submissions)
      break
    default: // default
      filtered.sort((a, b) => a.id - b.id)
  }

  return filtered
})

const paginatedProblems = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProblems.value.slice(start, end)
})

const solvedCount = computed(() => {
  return filteredProblems.value.filter(p => p.userStatus === 'solved').length
})

const attemptedCount = computed(() => {
  return filteredProblems.value.filter(p => p.userStatus === 'attempted').length
})

// 方法
const getDifficultyType = (difficulty) => {
  const types = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return types[difficulty] || 'info'
}

const formatNumber = (num) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSort = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const resetFilters = () => {
  searchKeyword.value = ''
  difficultyFilter.value = ''
  statusFilter.value = ''
  tagFilter.value = ''
  sortBy.value = 'default'
  currentPage.value = 1
}

const viewProblem = (problem) => {
  router.push(`/coding/problem/${problem.id}`)
}

const solveProblem = (problem) => {
  router.push(`/coding/editor/${problem.id}`)
}

const randomProblem = () => {
  const randomIndex = Math.floor(Math.random() * filteredProblems.value.length)
  const randomProblem = filteredProblems.value[randomIndex]
  if (randomProblem) {
    router.push(`/coding/problem/${randomProblem.id}`)
  } else {
    ElMessage.warning('没有可用的题目')
  }
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.problem-list {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  padding: 20px;
  position: relative;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}

.filter-left {
  .el-input {
    width: 300px;
    
    @media (max-width: 1024px) {
      width: 100%;
    }
  }
}

.filter-right {
  display: flex;
  gap: 12px;
  
  @media (max-width: 1024px) {
    flex-wrap: wrap;
  }
  
  .el-select {
    width: 120px;
    
    @media (max-width: 768px) {
      flex: 1;
      min-width: 100px;
    }
  }
}

.problem-stats {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  
  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.stat-item {
  text-align: center;
  
  .stat-number {
    font-size: 24px;
    font-weight: 700;
    color: var(--el-color-primary);
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.problems-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.status-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  
  .solved {
    color: var(--el-color-success);
    font-size: 18px;
  }
  
  .attempted {
    color: var(--el-color-warning);
    font-size: 18px;
  }
  
  .not-started {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--el-border-color-light);
  }
}

.problem-title-cell {
  .title {
    font-weight: 500;
    margin-bottom: 8px;
    color: var(--el-text-color-primary);
    cursor: pointer;
    
    &:hover {
      color: var(--el-color-primary);
    }
  }
  
  .tags {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
  }
}

.acceptance-rate {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.submissions-count {
  font-weight: 500;
  color: var(--el-text-color-secondary);
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.floating-actions {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 100;
  
  .random-btn {
    width: 56px;
    height: 56px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    
    &:hover {
      transform: scale(1.1);
    }
  }
}

:deep(.el-table) {
  .el-table__row {
    cursor: pointer;
    
    &:hover {
      background-color: var(--el-fill-color-extra-light);
    }
  }
}

@media (max-width: 768px) {
  .problems-container {
    padding: 12px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
    
    .el-button {
      font-size: 12px;
      padding: 4px 8px;
    }
  }
  
  .floating-actions {
    bottom: 20px;
    right: 20px;
    
    .random-btn {
      width: 48px;
      height: 48px;
    }
  }
}
</style>
